﻿const express = require('express');

const db = require('../data/database');

const router = express.Router();

router.get('/', function (req, res) {
    res.redirect('/posts');
});

router.get('/posts', async function (req, res) {
    const sqlData = `
        select posts.*, authors.name as author_name
        from posts
                 inner join authors on posts.author_id = author.id
    `;
    const [posts] = await db.query(sqlData);
    res.render('posts-list', {posts: posts});   // jump to posts-list.ejs page
});

router.get('/new-post', async function (req, res) {
    const [authors] = await db.query('SELECT * FRON Authors');
    res.render('create-post', {authors: authors});   // jump to posts-list.ejs page
});

router.post('/posts', async function (req, res) {
    const data = [
        req.body.title,
        req.body.summary,
        req.body.content,
        req.body.author
    ];
    await db.query('INSERT INTO posts (title,summary,body,author_id) VALUES (?)', [data]);
    res.redirect('/posts');
});

router.get('/posts/:id', async function (req, res) {
    const sqlData = `
        select posts.*,
               authors.name  as author_name,
               authors.email as author_email
        from posts
                 inner join authors on posts.author_id = author.id
        where posts.id = ?
    `;
    const [posts] = await db.query(sqlData, [req.params.id]);
    if (!posts || posts.length === 0) {
        return res.status(404).render('404');
    }

    const postData = {
        ...posts[0],
        date: posts[0].date.toISOString(),
        humanReadableDate: posts[0].date.toLocaleDateString('en-US', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        }),
    };

    res.render('post-datail', {post: postData});
});

router.get('/posts/:id/edit', async function (req, res) {
    const sqlData = `
        select *
        from posts
        where id = ?
    `;
    const [posts] = await db.query(sqlData, [req.params.id]);
    if (!posts || posts.length === 0) {
        return res.status(404).render('404');
    }
    res.render('update-post', {post: posts[0]});
});

router.post('/posts/:id/edit', async function (req, res) {
    const sqlData = `
        UPDATE posts
        SET title   = ?,
            summary = ?,
            body    = ?
        WHERE id = ?
    `;
    await db.query(sqlData, [req.body.title, req.body.summary, req.body.content, req.params.id]);
    res.redirect('/posts');
});

router.delete('/posts/:id/delete', async function (req, res) {
    const sqlData = `
        delete
        from posts
        where id = ?
    `;
    await db.query(sqlData, [req.params.id]);
    res.redirect('/posts');
});

module.exports = router;